package com.weibo.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.weibo.entity.JianceWeibo;
import com.weibo.service.JianceFenleiService;
import com.weibo.service.JianceWeiboService;
import com.weibo.util.Page;

public class JianceWeiboServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		
		String add = request.getParameter("add");
		String delete = request.getParameter("delete");
		String nicheng = request.getParameter("nicheng");
		String weibo_id = request.getParameter("weibo_id");
		String fenlei_id = request.getParameter("fenlei_id");
		String fenlei_name = request.getParameter("fenlei_name");
		String id = request.getParameter("id");
		
		JianceWeiboService jw = new JianceWeiboService();
		JianceFenleiService jfs = new JianceFenleiService();
		JianceWeibo weibo = null;
		if("add".equals(add)){
			weibo = new JianceWeibo();
			if(fenlei_id != null){
				int fenlei_id_int  = Integer.parseInt(fenlei_id);
				weibo.setFenlei_id(fenlei_id_int);
			 }
			weibo.setFenlei_name(fenlei_name);
			weibo.setNicheng(nicheng);
			if(weibo_id != null){
				int weibo_id_int  = Integer.parseInt(weibo_id);
				weibo.setWeibo_id(weibo_id_int);
			 }
			jw.add(weibo);
		}
		if("delete".equals(delete)){
			int idint = 0;
			if(id != null){
				idint = Integer.parseInt(id);
			}
			jw.delete(idint);
		}
		
		
		Page page = new Page();
		List<Object> list = jw.findAll();//获取全部数据
		List<Object> list_fenlei = jfs.findAll();
		int maxPage = page.getMaxPage(list, 5);//获取最大页码		
		
		String temp = request.getParameter("page");	//获取请求页码	
		int nowPage = page.getPage(list, 5, temp);//验证页码的有效性
		
		List<Object> initList = page.getInitPage(list, nowPage, 5);//获取指定页码的数据
		
		request.setAttribute("nowPage", nowPage);//当前页
		request.setAttribute("maxPage", maxPage);//最大页
		request.setAttribute("initlist", initList);//数据
		
		request.setAttribute("weiboshu", list.size());//数据
		request.setAttribute("list_fenlei", list_fenlei);//数据
	    request.getRequestDispatcher("/jiance_weibo.jsp").forward(request, response);
	    
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
